package com.itheima.reggie.common;

import com.itheima.reggie.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLNonTransientException;

@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            String value = message.split(" ")[2];
            return R.error(value + "已存在！");
        }
        System.out.println(e.getMessage());
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e) {
        return R.error(e.getMessage());
    }
}
